import Client from '../Client'
import { generateDid, getUnixTimestamp, md5, getInt, hex2bin, hex, binEncrypt } from './helper'
import config from '../Config'

export default class WSProxyClient extends Client {
  _keepLiveTime = 45
  did = generateDid()
  _kd = ''

  constructor (room) {
    super('wsproxy.douyu.com', 6673)
    this.room = room
  }

  _onOpen () {
    this._userLogin()
  }

  _onMessage (msg) {
    if (config._App.Debug) console.debug('receive msg', `[${msg.type}]`, msg)
    switch (msg.type) {
      case 'loginres':
        this.userid = msg.userid
        this.username = msg.username
        this.nickname = msg.nickname
        this.roomgroup = getInt(msg, 'roomgroup')
        this._requestKey()
        this._qradsr()
        if (this.roomgroup !== 0) this.sendMsg({ type: 'reqog', uid: this.userid })
        if (this._keepLiveInterval) clearInterval(this._keepLiveInterval)
        this._keepLiveInterval = setInterval(this._keepLive.bind(this), 1e3 * this._keepLiveTime)
        this.once('close', () => clearInterval(this._keepLiveInterval))
        this._keepLive()
        break
      case 'keeplive':
        let binArr = hex2bin(msg.kd)
        if (binArr) {
          try {
            binEncrypt(binArr)
            this._kd = hex(binArr)
          } catch (e) {
            this._kd = ''
          }
        } else {
          this._kd = ''
        }
        break
      case 'tsboxb':
      case 'tslist':
        this.emit('pack', msg)
        break
    }
  }

  /* send msg pack */

  _userLogin () {
    // 目前使用匿名auth, 和auth有关的参数: username, password, ltkid, biz, stk
    let pack = {
      type: 'loginreq',
      username: '',
      password: '',
      roomid: this.room,
      ltkid: '',
      biz: '',
      stk: '',
      dfl: '',
      ct: 0,
      devid: this.did,
      rt: getUnixTimestamp(),
      pt: 2,
      ver: '20180222',
      aver: 'H5_2018062731beta'
    }
    pack.vk = md5(`${pack.rt}r5*^5;}2#\${XF[h+;'./.Q'1;,-]f'p[${pack.devid}`)
    this.sendMsg(pack)
  }

  _keepLive () {
    this.sendMsg({
      type: 'keeplive',
      tick: getUnixTimestamp(),
      vbw: 0,
      cdn: '',
      kd: this._kd
    })
  }

  _userJoinGroup () {
    if (!this.isJoinGroup && this.isConnected) {
      this.isJoinGroup = true
      this.sendMsg({
        type: 'joingroup',
        rid: this.room,
        gid: 88 // 应该是只影响弹幕, 不影响礼物消息
      })
    }
  }

  _requestKey () {
    this.sendMsg({
      type: 'h5ckreq',
      rid: this.room,
      ti: '220120180630' // ver, 可能会变化
    })
  }

  _qradsr () {
    this.sendMsg({
      type: 'qradsr',
      rid: this.room,
      xhashkeyx: this.room
    })
  }
}
